import { Controller, Get, Post, Put, Delete, Body, Param, UseGuards, Request } from '@nestjs/common';
import { MenuService } from './menu.service';
import { Menu } from './menu.entity';
import { CasbinService } from '../casbin/casbin.service';
import { JwtHttpGuard } from '../auth/jwt-http.guard';
import { CreateMenuDto } from './dto/create-menu.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';

@Controller('menu')
@UseGuards(JwtHttpGuard)
export class MenuController {
  constructor(
    private menuService: MenuService,
    private casbinService: CasbinService,
  ) {}

  /**
   * 获取所有菜单列表
   */
  @Get('list')
  async getAllMenus(): Promise<Menu[]> {
    return await this.menuService.findAll();
  }

  /**
   * 获取当前用户有权限的菜单树
   */
  @Get('tree')
  async getMenuTree(@Request() req): Promise<Menu[]> {
    const user = req.user;
    
    // 获取所有菜单
    const allMenus = await this.menuService.findAll();
    
    // 根据权限过滤菜单
    const filteredMenus = await this.menuService.filterMenusByPermissions(allMenus, user);
    
    // 构建菜单树
    return await this.menuService.buildMenuTree(filteredMenus);
  }

  /**
   * 获取所有菜单树（管理员使用）
   */
  @Get('tree/all')
  async getAllMenuTree(): Promise<Menu[]> {
    const allMenus = await this.menuService.findAll();
    return await this.menuService.buildMenuTree(allMenus);
  }

  /**
   * 添加菜单
   */
  @Post()
  async addMenu(@Body() createMenuDto: CreateMenuDto): Promise<Menu> {
    const newMenu = await this.menuService.create(createMenuDto);
    
    // 如果菜单有权限标识，同步到Casbin
    if (newMenu.permission) {
      // 这里可以根据需要添加默认策略
      // 示例：await this.policyService.create({ptype: 'p', v0: 'role', v1: newMenu.permission, v2: 'read'});
    }
    
    return newMenu;
  }

  /**
   * 修改菜单
   */
  @Put()
  async updateMenu(@Body() updateMenuDto: UpdateMenuDto): Promise<Menu | null> {
    return await this.menuService.update(updateMenuDto.id, updateMenuDto);
  }

  /**
   * 删除菜单
   */
  @Delete(':id')
  async deleteMenu(@Param('id') id: string): Promise<void> {
    // 删除菜单
    await this.menuService.delete(parseInt(id));
    
    // TODO: 同步删除Casbin中的相关策略
  }
}